/*
*
* Watermarkable
*
* Attach tooltip which removed on focus to element
* 
*
* Version 0.01
* @requires jQuery v1.5 or later
*
* Copyright (c) 2011 Demchenko Oleg, Kurbatoff Oleg
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php


Options:

* tooltipText
Text, showed on tooltip

*
*  color
Tooltip color
*/
(function ($) {

    $.fn.watermarkable = function (options) {
        var opt = {
            tooltipText: "",
            color: "Gray"
        };
        $.extend(opt, options);


        return this.each(function (i) {
            var el = $(this);
            var isPassword = (el.attr("type") == "password") ? true : false;
            if (isPassword){
                attachTooltipToPasswordField(el, opt.tooltipText, opt.color);
            } else {
                attachTooltipToField(el, opt.tooltipText, opt.color);
            }
        });
    }

    function attachTooltipToPasswordField(field, tooltipText, color){
        if ($(field).attr("type") == "password"){
            var label = document.createElement("div");
            $(label).width($(field).width());
            $(label).height($(field).height());
            $(label).css("top", $(field).offset().top + "px")
                .css("left", $(field).offset().left + "px")
                .css("margin-left", "-" + $(label).width() + "px")
                .css("display", "inline-block")
                .css("cursor", "text")
                .css("color", color)
                .css("font-size", $(field).css("font-size"));
            $(label).html(tooltipText);
            $(field).focus(function(event){
                $(this).next().hide();
            });
            $(field).blur(function(event){
                if($(field).val() == ""){
                    $(field).next().css("display", "inline-block");
                }
            });
            $(label).click(function(){
                $(this).hide();
                $(this).prev().focus();
            });
            $(field).after($(label));
        }
    }

    function attachTooltipToField(field, tooltipText, color){
        field.val(tooltipText);
        field.css("color", color);
        field.focus(function(event){
            if($(this).val() == tooltipText){
                $(this).val("");
                $(this).css("color", "");
            }
        });
        field.blur(function(event){
            if($(this).val() == ""){
                $(this).val(tooltipText);
                $(this).css("color", color);
            }
        });
    }


})(jQuery);